package cn.micro.keep.accounts.service.impl;

import cn.micro.keep.accounts.common.utils.SecurityUtil;
import cn.micro.keep.accounts.entity.AccountDimShareGroupUser;
import cn.micro.keep.accounts.entity.AccountOdsShareGroupApplyJoinRecord;
import cn.micro.keep.accounts.entity.dto.ApplyJoinGroupSearch;
import cn.micro.keep.accounts.entity.dto.ApproveJoinGroupDTO;
import cn.micro.keep.accounts.entity.vo.ApplyJoinGroupVO;
import cn.micro.keep.accounts.mapper.AccountOdsShareGroupApplyJoinRecordMapper;
import cn.micro.keep.accounts.service.AccountDimShareGroupUserService;
import cn.micro.keep.accounts.service.AccountOdsShareGroupApplyJoinRecordService;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 申请加入分享组表 服务实现类
 * </p>
 *
 * @author 柘阳科技
 * @since 2023-11-10
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AccountOdsShareGroupApplyJoinRecordServiceImpl extends ServiceImpl<AccountOdsShareGroupApplyJoinRecordMapper, AccountOdsShareGroupApplyJoinRecord> implements AccountOdsShareGroupApplyJoinRecordService {

    private final AccountDimShareGroupUserService shareGroupUserService;

    @Override
    @DSTransactional
    public boolean approveJoinGroup(ApproveJoinGroupDTO dto) {
        boolean result = false;
        LambdaQueryWrapper<AccountOdsShareGroupApplyJoinRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccountOdsShareGroupApplyJoinRecord::getId,dto.getId())
                .eq(AccountOdsShareGroupApplyJoinRecord::getApplyUserId, SecurityUtil.getUserId());
        AccountOdsShareGroupApplyJoinRecord record = this.getOne(queryWrapper);
        if (record == null){
            throw new RuntimeException("记录不存在");
        }
        record.setStatus(dto.getStatus());
        record.setApplyDesc(dto.getApproveDesc());
        if (this.updateById(record)){
            AccountDimShareGroupUser groupUser = new AccountDimShareGroupUser();
            groupUser.setShareGroupId(record.getShareGroupId());
            groupUser.setUserId(record.getApplyUserId());
            result = shareGroupUserService.save(groupUser);
        }
        return result;
    }

    @Override
    public List<ApplyJoinGroupVO> listApplyJoinGroup(ApplyJoinGroupSearch search) {
        PageHelper.startPage(search.getPageNum(), search.getPageSize());
        return this.baseMapper.queryApplyJoinGroup(search);
    }
}
